package cn.kgc.config;

import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author kk
 * @version 1.0
 */
@EnableRabbit
@Configuration
@SuppressWarnings("all")
public class RabbitConnectionConfig {
    @Value("${mq.address}")
    private String address;

    @Value("${mq.username}")
    private String username;

    @Value("${mq.password}")
    private String password;

    @Value("${mq.vhost}")
    private String vhost;

    @Bean
    public ConnectionFactory connectionFactory(){
        CachingConnectionFactory connectionFactory=new CachingConnectionFactory();
        //地址
        connectionFactory.setAddresses(address);
        //虚拟主机
        connectionFactory.setVirtualHost(vhost);
        //账号
        connectionFactory.setUsername(username);
        //密码
        connectionFactory.setPassword(password);
        //确认信息是否进入到队列
        connectionFactory.setPublisherReturns(true);
        //确认信息是否进入到交换机
        connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
        connectionFactory.createConnection();
        return connectionFactory;
    }

    /**
     * RabbitAdmin是Spring AMQP提供的管理工具，可以自动声明交换器、队列和绑定。
     * 设置了setAutoStartup(true)，这意味着应用启动时RabbitAdmin会自动初始化并创建所需的AMQP组件。
     */
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
        RabbitAdmin rabbitAdmin=new RabbitAdmin(connectionFactory);
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }
}